import Vue from 'vue'
import Router from 'vue-router'

import { constantRouterMap } from './router.config.js'

// hack router push callback
const originalPush = Router.prototype.push
Router.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(Router)
const createRouter = () =>{
  return new Router({
    // mode: 'history', // 如果你是 history模式 需要配置vue.config.js publicPath
    // base: process.env.BASE_URL,
    // scrollBehavior: () => ({ y: 0 }),
    routes: constantRouterMap
  })
}
  
let router = createRouter();

let back = router.__proto__.back.bind(router)
let backParams = {};
let backInfo = {};
let fromPath = "";
router.__proto__.backParams = function(){
  const temp = backParams[router.currentRoute.path] || {}
  backParams[router.currentRoute.path] = {};
  return temp;
}

router.__proto__.back = function(params){
  fromPath = this.currentRoute.path
  backInfo = {
    fromPath,
    params
  };
  back();
}.bind(router);

router.beforeEach((to, from, next) => {
  if(from.path == backInfo.fromPath){
    backParams[to.path] = backInfo.params
  }
  backInfo = {};
  next();
});

export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}


export default router

export const nativeRouter = () => {
  NApp.AddJsAPI('Rollback', () => {
    let temp = router.currentRoute;
    if ([
        "Product",
        "Home",
        "Mine",
      ].indexOf(temp.name) > -1) {
      return NBase.closeApp();
    }
    router.back();
  });
};